package libra;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.annotation.NacosValue;

@RestController
public class TestController {
	/**
	 * 在Nacos整合SpringCloud之后
	 * 我们无法再通过@NacosValue获取配置属性值
	 * 只能使用@Value来进行配置属性值的获取、注入
	 */
	@Value("${msg}")
	private String msg;
	@NacosValue(value = "${refresh}", autoRefreshed = true)
	private String refresh;
	@NacosValue("${version}")
	private Double version;
	
	@Autowired
	private LoadConfig loadConfig;

	/**
	 * 在Nacos整合SpringCloud之后
	 * 我们无法再通过@NacosInjected获取Nacos的ConfigService实例对象
	 * 	即无法直接手动编程调用API进行操作
	 */
	@NacosInjected
	private ConfigService configService;
	
	@PostConstruct
	public void init() {
		// 获取NacosConfig的状态
		System.out.println( "获取configService实例对象->" + configService );
//		System.out.println( "configService.getServerStatus()->" + configService.getServerStatus() );
		System.out.println( "获取loadConfig实例对象类型->" + loadConfig.getClass().getName() );
	}
	
	/**
	 * 获取SpringEnvironment运行时环境
	 */
	@Autowired
    ConfigurableEnvironment springEnv;
	/**
	 * 通过当前运行环境Environment获取配置
	 * 原因NacosConfig会把配置文件拉取到当前应用，并封装为PropertySource对象添加到Environment对象中
	 */
	public Map getValFromEnv() {
		return new HashMap<>() {{
			put("msg", springEnv.getProperty("msg").toString());
			put("refresh", springEnv.getProperty("refresh").toString());
			put("version", springEnv.getProperty("version").toString());
		}};
	}
	
	@RequestMapping("getData")
	public Object getDate(HttpServletRequest req, HttpServletResponse resp) {
		// 当前类通过@Value获取配置，但是不包含@RefreshScope刷新
		HashMap<Object, Object> local = new HashMap<>() {{
			put("msg", msg);
			put("refresh", refresh);
			put("version", version);
		}};
		// 自定义配置组件通过@Value获取配置，包含@RefreshScope刷新
		HashMap<Object, Object> component = new HashMap<>() {{
			put("msg", loadConfig.getMsg());
			put("refresh", loadConfig.getRefresh());
			put("version", loadConfig.getVersion());
			put("lc_toString", loadConfig.toString());
		}};
		return new HashMap<>() {{
			put("local", local);
			put("component", component);
			put("environment", getValFromEnv());
		}};
	}
	
}
